﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Newtonsoft.Json.Linq;

namespace LocalServer.Utils
{
    public class HttpServer
    {
        public static event MMSendMsg sendMsgEvent;

        private int port = 9000;
        private HttpListener httpListener;

        public HttpServer()
        {
            this.httpListener = new HttpListener();
        }
        public HttpServer(int port) : this()
        {
            this.port = port;
        }
        public void Run()
        {
            this.httpListener.Prefixes.Add(string.Format("http://+:{0}/", this.port));
            this.httpListener.Start();
            this.httpListener.BeginGetContext(new AsyncCallback(GetContext), this.httpListener);
            Console.WriteLine("Listen Port:" + port);

            JObject jsonObj = new JObject();
            jsonObj.Add("type", "ServerStarted");

            SendMsg(jsonObj);
        }
        public bool IsListening()
        {
            return httpListener.IsListening;
        }
        private void GetContext(IAsyncResult ar)
        {
            HttpListener httpListener = ar.AsyncState as HttpListener;
            HttpListenerContext context = httpListener.EndGetContext(ar);  //接收到的请求context（一个环境封装体）

            httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener);  //开始 第二次 异步接收request请求

            HttpListenerRequest request = context.Request;  //接收的request数据
            HttpListenerResponse response = context.Response;  //用来向客户端发送回复

            string rawData;
            using (StreamReader reader = new StreamReader(request.InputStream))
            {
                rawData = reader.ReadToEnd();
            }
            try
            {
                Task.Run(() =>
                {
                    JObject jsonObj = JObject.Parse(rawData);
                    //SendMsg(jsonObj);
                    //Console.Write(jsonObj.ToString());
                    MessageDealUtils.messageDeal(jsonObj);
                });
                
            }
            catch (Exception ex)
            {

            }
            
            using (Stream output = response.OutputStream)  //发送回复
            {
                byte[] buffer = Encoding.UTF8.GetBytes("ok");
                output.Write(buffer, 0, buffer.Length);
            }
        }

        public void SendMsg(JObject obj)
        {
            if (sendMsgEvent != null)
            {
                sendMsgEvent(obj);
            }
        }
    }
}
